//
//  weibo3AppDelegate.m
//  weibo3
//
//  Created by Tian Wu on 11-4-8.
//  Copyright 2011年 nfsysu. All rights reserved.
//

#import "weibo3AppDelegate.h"
#import "RootViewController.h"

extern RootViewController* rootView;

@interface weibo3AppDelegate(Private)
- (void)setNextTimer:(NSTimeInterval)interval;
@end

@implementation weibo3AppDelegate

@synthesize window, statusItem;

- (void)autoRefresh:(NSTimer*)timer
{
    [lastRefreshDate release];
    lastRefreshDate = [[NSDate date] retain];
    
    
    [rootView didBackgroundCheck];
    
    [self setNextTimer:autoRefreshInterval];
}

- (void)applicationDidBecomeActive:(NSNotification *)aNotification{
    
        if (autoRefreshTimer) {
        [autoRefreshTimer invalidate];
        autoRefreshTimer = nil;
    }
    
}

- (void)applicationWillResignActive:(NSNotification *)aNotification{
    
    if (lastRefreshDate == nil) {
        lastRefreshDate = [[NSDate date] retain];
    }
    else if (autoRefreshInterval) {
        NSDate *now = [NSDate date];
        NSTimeInterval diff = autoRefreshInterval - [now timeIntervalSinceDate:lastRefreshDate];
        if (diff < 0) {
            diff = 2.0;
        }
        [self setNextTimer:diff];
    }
    
}

- (void)setNextTimer:(NSTimeInterval)interval
{
    autoRefreshTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(autoRefresh:) userInfo:nil repeats:false];    
}

- (void) timerInit{
    int interval = 1;
    autoRefreshInterval = interval * 60;
    //if (autoRefreshInterval < 180) autoRefreshInterval = 180;
    [self setNextTimer:autoRefreshInterval];
}



- (void) testtesttest{
    
    NSLog(@"testing");
    
}

- (void)handleURLEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
{
    NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
    
    NSLog(@"recived url:%@",url);
    NSString* pin = [[url componentsSeparatedByString:@"oauth_verifier="] lastObject];
	if ([pin length] > 0) {
		[[NSUserDefaults standardUserDefaults] setObject:pin forKey:@"accessTokenVerifier"];
        [rootView requestAccessToken];
		[NSApp stopModal];
	}
    
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    mainWindow = [[RootViewController alloc] init];
    extern weibo3AppDelegate *appDelegate;
    appDelegate = self;
    
    [[rootView window] setFrameUsingName:@"mainWindowFrame"];
    
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
    
    if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"displayNotif"] isEqualToString:@"ON"]) {
        self.statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
    }
    [self.statusItem setImage:[NSImage imageNamed:@"weibomini.png"]];
    [self.statusItem setAlternateImage:[NSImage imageNamed:@"weibominiwi.png"]];
    [self.statusItem setAction:@selector(showSelfWindow)];
    
    [self.statusItem setHighlightMode:YES];
    
    [self.statusItem setMenu:nil];
        
    if (!([[[NSUserDefaults standardUserDefaults] stringForKey:@"accessTokenSecret"] length] > 0)){
        [mainWindow didLogin:self];
    }
    [mainWindow showWindow:self];


    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"autologin"] && [[NSUserDefaults standardUserDefaults] objectForKey:@"accessTokenSecret"]) {
        
        User *user = [rootView verifyUser];
        
        if ([user name] == nil) {
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"password"];
            NSAlert *alert = [NSAlert alertWithMessageText:@"发生了一点错误" defaultButton:@"重新输入" alternateButton:nil otherButton:nil informativeTextWithFormat:@"登录失败！请检查：1.帐号密码是否正确；2.是否已连接到互联网。"];
            [alert beginSheetModalForWindow:[mainWindow window] modalDelegate:self didEndSelector:nil contextInfo:NULL];
        }
        else{
            //[rootView loginInit];
            [self timerInit];
        }

        
    }
    else{
        //[mainWindow didLogin:self];
    }
    
}


    
    
    

- (IBAction) hideApplication:(id) sender{
    
    [NSApp hide:self];
    
}

- (IBAction) toNextPage:(id) sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"toNextPage" object:nil];
}
- (IBAction) toPrePage:(id) sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"toPrePage" object:nil];
}
- (IBAction) scrollDownARow:(id) sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"scrollDownARow" object:nil];
}
- (IBAction) scrollUpARow:(id) sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"scrollUpARow" object:nil];
}
- (IBAction) viewDetail:(id) sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"viewDetail" object:nil];
}

- (void) showSelfWindow{
    
    [NSApp activateIgnoringOtherApps:YES];
    [[rootView window] makeKeyAndOrderFront:self];
    
}

- (void) viewAndRefreshStatus{
    if ([NSApp isActive]) {
        [rootView refreshStatusWithFunction:0 Page:1];
    }
    else{
        [rootView selectTabByIndex:0];
        [self showSelfWindow];
    }
    
    
}

- (void) viewAndRefreshMentions{
    if ([NSApp isActive]) {
        [rootView refreshStatusWithFunction:1 Page:1];
    }
    else{
        [rootView selectTabByIndex:1];
        [self showSelfWindow];
    }
}

- (void) viewAndRefreshComments{
    if ([NSApp isActive]) {
        [rootView refreshStatusWithFunction:3 Page:1];
    }
    else{
        [rootView selectTabByIndex:3];
        [self showSelfWindow];
    }
}

- (void) directToDM{
    NSString *url = @"http://weibo.com/messages";
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
    [rootView resetCountWithType:3];
    [rootView didBackgroundCheck];
}

- (void) directToFollower{
    
    NSString *url = @"http://weibo.com";
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];
    [rootView resetCountWithType:4];
    [rootView didBackgroundCheck];
    
}

- (void) changeStatusItemTo:(BOOL) status{
    
    if (status) {
        [self.statusItem setImage:[NSImage imageNamed:@"weibominihi.png"]];
    }
    else{
        [self.statusItem setImage:[NSImage imageNamed:@"weibomini.png"]];
    }
    
}

-(BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
    [window makeKeyAndOrderFront:nil];
    return YES;
}



- (void)applicationWillTerminate:(NSNotification *)aNotification{
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"logined"];
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"autologin"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"accessTokenKey"];
		[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"accessTokenSecret"];
		[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"accessTokenVerifier"];
    }
    [[rootView window] saveFrameUsingName:@"mainWindowFrame"];
    
}

- (void)dealloc
{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"logined"];
    [mainWindow release];
    [statusItem release];
    [super dealloc];
}

@end
